package com.fire.control.system.config.interceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.fire.control.system.config.listener.MyServletContextListener;
import com.fire.control.system.dto.UserDTO;
import com.fire.control.system.statics.Key;
import com.fire.control.system.statics.ResponseMessage;
import com.fire.control.system.support.protocol.comman.ResponseJsonProtocol;
import com.fire.control.system.support.protocol.comman.ResponseProtocol;
import com.fire.control.system.support.util.HttpUtil;
import com.fire.control.system.support.util.StaticValue;


/**
* @ClassName: WebInterceptor
* @Description: TODO(Web拦截器)
* @author wanbo
* @date 2017年6月7日 上午12:50:19
*/
public class WebInterceptor implements HandlerInterceptor {
	
	private static final Logger logger = LoggerFactory.getLogger(WebInterceptor.class);
	
	public String[] excludeUrls = StaticValue.excludeUrls;
	
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)throws Exception {
    	//排除URL
    	String url = request.getServletPath();
    	for (String excludeUrl : excludeUrls) {
    		if(url.contains(excludeUrl)){
    			return true;
    		}
    	}
        logger.info("--------->WebInterceptor验证用户合法性(Controller方法调用之前):"+url);
        
        
        
        
        
        /***********************虚拟登入信息 start****************
        {
        	String userId = request.getParameter(Key.userId.toString());
            if(StringUtils.isEmpty(userId)){
            	userId = request.getHeader(Key.userId.toString());
            }
            if(StringUtils.isEmpty(userId)){
            	HttpUtil.outputJson(response, ResponseMessage.CODE_400.messageToProtocol(new ResponseJsonProtocol()).toString());
            	return false;
            }
            UserDTO userDto = MyServletContextListener.userService.getUserInfo(userId);
            
            request.getSession().setAttribute(Key.session_key_lora_user_id.toString(), userDto);
        }
        **********************虚拟登入信息 end*****************/
        
        
        
        
        /**验证user*/
        UserDTO user = (UserDTO) request.getSession().getAttribute(Key.session_key_lora_user_id.toString());
        if(user!=null && StringUtils.isNotEmpty(user.getUserId())){
        	return true;
        	//测试阶段放开权限验证
        	/*String urls = MyServletContextListener.resourceService.getResourcesUrlByuid(user.getUserId());
        	if(urls.contains(url)){
        		return true;
        	}*/
        }else{
        	ResponseProtocol protocol = new ResponseJsonProtocol();
        	ResponseMessage.CODE_DEFINED.messageToProtocol(protocol).setMessage("用户不存在");
        	HttpUtil.outputJson(response, protocol.toString());
        }
        
        return false;
    }
    
    //System.out.println(">>>WebInterceptor>>>>>>>请求处理之后进行调用，但是在视图被渲染之前（Controller方法调用之后）");
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,ModelAndView modelAndView) throws Exception {
    	/*String url = request.getServletPath();
    	Object object = request.getSession().getAttribute(Key.session_key_lora_user_id.toString());
    	if(object!=null){
    		UserDTO user = (UserDTO)object;
    		String userId = user.getUserId();
			MyServletContextListener.systemLogService.addSystemLog(userId,url);
    	}*/
    }
    
    //System.out.println(">>>WebInterceptor>>>>>>>在整个请求结束之后被调用，也就是在DispatcherServlet 渲染了对应的视图之后执行（主要是用于进行资源清理工作）");
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)throws Exception {
    }
    
    

}